package red.yancloud.www.ui.fragment


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_home.*
import org.jsoup.Jsoup

import red.yancloud.www.R
import red.yancloud.www.base.BaseWebViewFragment
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.VideoInfo
import red.yancloud.www.ui.activity.*
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.UrlUtils
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.*

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/5 14:59
 * E_Mail：yh131412hys@163.com
 * Describe：首页
 * Change：
 * @Version：V1.0
 */
class HomeFragment : BaseWebViewFragment() {

    private lateinit var mainActivity:MainActivity

    override val layoutId: Int
        get() = R.layout.fragment_home

    override fun onAttach(context: Context) {
        super.onAttach(context)

        mainActivity = context as MainActivity
    }

    override fun configView() {
        super.configView()

        mRefreshLayout.setEnableLoadMore(false)
    }

    override fun initData() {

        mUrl="${Constants.API_BASE_RED_CLOUD_URL}Index"

//        parentView.findViewById<AppCompatImageView>(R.id.homeFragment_title_iv).setOnClickListener {
//
////            startActivity(Intent(mContext,TestActivity::class.java))
//            startActivity(Intent(mContext,SearchActivity::class.java))
//        }
//        parentView.findViewById<AppCompatTextView>(R.id.homeFragment_search_tv).setOnClickListener {
//
//            ToastUtils.showToast("搜索")
//        }
    }

//    不能直接用id的原因，你xml没有载入，会导致使用id的时候会报空指针，如果需要使用，在onCreateView return view后，在onViewCreate函数中使用Id直接调用，onViewCreate会在onCreateView后执行
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

//        homeFragment_title_iv.setOnClickListener {
//            startActivity(Intent(mContext,SearchActivity::class.java))
//        }
    }

    @SuppressLint("AddJavascriptInterface")
    override fun addJavaScriptInterface() {

        mWebView.addJavascriptInterface(object : Any() {

            @JavascriptInterface
            fun loadData(){
                mHandler.post(object :Runnable{
                    override fun run() {
                        mWebView.loadUrl("javascript:waves(" + UrlUtils.makeJsonText() + ")")
                        if (!(mContext as Activity).isFinishing) {
                            loadingDialog.dismiss()
                        }
                    }
                })
            }

            @JavascriptInterface
            fun gotolink(url: String,type: String) {

                mHandler.post {

                    ToastUtils.showToast("$url=====$type")

//                    type 1、内部 2、外部
                    if (!TextUtils.isEmpty(url)) {

                        if (type == "1") {

                            startActivity(
                                Intent(mContext, NewsInfoActivity::class.java)
                                    .putExtra(
                                        "url",
                                        url)
                                    .putExtra("model","banner")
                                    .putExtra("id","")
                            )
                        }else if (type == "2"){

                            AppUtils.openBrowser(mContext,url)
                        }
                    }
                }
            }

            @JavascriptInterface
            fun gotourl(url: String,model: String,id: String) {
                mHandler.post {

                    startActivity(Intent(mContext, NewsInfoActivity::class.java)
                        .putExtra("url",Constants.BASE_RED_CLOUD_HOST_URL+url)
                        .putExtra("model",model)
                        .putExtra("id",id)
                    )
                }
            }

            /**
             * vkey：指定大页面
             * vtoclas：区分小分类
             */
            @JavascriptInterface
            fun gotopage(key: String,value: String) {
                mHandler.post {

                    when (key) {
//                        延云知库
                        "zhi" -> {

                            mainActivity.mainActivity_vP.currentItem=Constants.RedCloudMainType.MAIN_REPOSITORY_VIEW
                        }
//                        延云阅读
                        "read" -> {

                            mainActivity.mainActivity_vP.currentItem=Constants.RedCloudMainType.MAIN_READ_VIEW
                        }
//                        延云视听
                        "video" -> {

                            startActivity(Intent(mContext,VideoListActivity::class.java))
                        }
//                        更多分类
                        "more" -> {

                            mainActivity.mainActivity_vP.currentItem=Constants.RedCloudMainType.MAIN_SORT_VIEW
                        }
//                        广播消息
                        "eventnews" -> {

                            startActivity(Intent(mContext,BroadcastMessageActivity::class.java).putExtra("type","首页广播消息列表"))
                        }
//                        专家团队
                        "entry" -> {

                            startActivity(Intent(mContext, ExpertTeamMoreActivity::class.java))
                        }
                    }
                }
            }

            @JavascriptInterface
            fun showbook(bookId: String) {
                mHandler.post {

                    startActivity(Intent(mContext,BookInfoActivity::class.java)
                        .putExtra("bookId",bookId)
                        .putExtra("url","${Constants.API_BASE_RED_CLOUD_URL}article/?bid=$bookId"))
                }
            }

            @JavascriptInterface
            fun showvideo(videoId: String,fileAddress: String,content: String) {
                mHandler.post {

                    val videoSource = Jsoup.parse(URLDecoder.decode(content)).select("video").select("source").attr("src")
                    Log.d("showvideo",videoSource)

                    if (!TextUtils.isEmpty(videoSource)) {

                        startActivity(Intent(mContext,VideoInfoActivity::class.java)
                            .putExtra("id",videoId)
                        )
                    }

                    if (!TextUtils.isEmpty(fileAddress)) {

                        if (fileAddress.startsWith("http")) {

                            AppUtils.openBrowser(mContext, fileAddress)
                        }else{

//                            AppUtils.openBrowser(mContext, Constants.BASE_RED_CLOUD_HOST_URL+fileAddress)
                            startActivity(Intent(mContext,VideoInfoActivity::class.java)
                                .putExtra("id",videoId)
                            )
                        }
                    }

//                    loadingDialog.show()
//
//                    RedCloudApis.getInstance().getVideo(videoId, object : Observer<VideoInfo> {
//                        override fun onComplete() {
//                        }
//
//                        override fun onSubscribe(d: Disposable) {
//                        }
//
//                        override fun onNext(t: VideoInfo) {
//
//                            if (t.code == Constants.SYSTEM_OK&&t.data!=null&&t.data.video!=null) {
//
//                                val videoSource = Jsoup.parse(t.data.video.content).select("video").select("source").attr("src")
//                                if (!TextUtils.isEmpty(videoSource)) {
//
//                                    startActivity(Intent(mContext,VideoInfoActivity::class.java)
//                                        .putExtra("id",videoId)
//                                    )
//                                }
//
//                                val fileAddress = t.data.video.fileaddress
//                                if (!TextUtils.isEmpty(fileAddress)) {
//
//                                    if (fileAddress.startsWith("http")) {
//
//                                        AppUtils.openBrowser(mContext, fileAddress)
//                                    }else{
//
//                                        AppUtils.openBrowser(mContext, Constants.BASE_RED_CLOUD_HOST_URL+fileAddress)
//                                    }
//                                }
//                            }
//
//                            loadingDialog.dismiss()
//                        }
//
//                        override fun onError(e: Throwable) {
//
//                            loadingDialog.dismiss()
//                        }
//                    })
                }
            }

            @JavascriptInterface
            fun alert(alert: String) {
                mHandler.post {

                    ToastUtils.showToast(alert)
                }
            }
        },"demo")
    }
}
